"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.joinErrorMiddleware = void 0;
const defines_1 = require("../lib/defines");
const Classrooms_1 = require("../lib/Classrooms");
const socket_message_1 = require("../utils/socket_message");
const log4js_1 = require("log4js");
const logger = (0, log4js_1.getLogger)('JoinHelper');
async function joinErrorMiddleware(app, io) {
    const { socket } = app.locals;
    const { userId, username, userType } = socket.handshake.query;
    const owner = { userId, username, userType };
    const JoinError = (msg) => (0, socket_message_1.errorMsg)('joined', msg, { owner });
    socket.use(async (event, next) => {
        const [name, params, cb] = event;
        if (name === defines_1.RequestMethod.join) {
            logger.debug('JoinHelper:join -------------------');
            const { room, uri } = params;
            if (!room) {
                return cb && cb(JoinError(`params: room ${JSON.stringify(room, null, 2)} must required!`));
            }
            const classroom = Classrooms_1.Classrooms.get(room.classId);
            if (!classroom) {
                return cb && cb(JoinError(`room: ${JSON.stringify(room, null, 2)} not found in rooms!`));
            }
            if (!classroom.pipeline) {
                return cb && cb(JoinError(`classroom: ${JSON.stringify(socket.handshake.query, null, 2)} connect error，please re-create the room!`));
            }
            const classMember = classroom.getMember(userId);
            if (classMember) {
                return cb && cb(JoinError(`member: ${JSON.stringify(socket.handshake.query, null, 2)} was already joined!`));
            }
        }
        next();
    });
}
exports.joinErrorMiddleware = joinErrorMiddleware;
